const app = getApp()

Page({
  data: {
    tabs: ['投票照片墙', '投票排行榜'],
    currentTab: 0,
    photoList: [
    ],
    showUpload: false,
    uploadImage: '',
    uploadImage: '',
    nickname: '',
    historyImage: '',     // 历史上传的图片
    vote_status: 0,       // 投票状态
    historyVotes: 0,      // 历史票数
    disableNickname: false,
    showSubmit: true,
    kvimg: '',
    staticUrl: app.globalData.staticUrl,
    phoneno: app.globalData.userInfo.phoneno,
    trueName: app.globalData.userInfo.trueName,

  },

  onShow: function () {
    if (app.checkislogin()) {
      this.getPhotos();  
    } else {
      wx.showModal({
        title: '请先登录',
        content: '需要登录后才能投票',
        confirmText: '去登录',
        cancelText: '取消',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    }
  },
  // 搜索
  onSearch(e) {
    const keyword = e.detail.value;
    this.getPhotos(keyword);
  },

  // 切换tab
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ currentTab: index });
    this.getPhotos();
  },
// 获取照片列表
getPhotos(keyword = '') {
  wx.showLoading({ title: '加载中...' });
  wx.request({
    url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/votelist',
    method: 'GET',
    data: {
      type: this.data.currentTab+1, 
      keywords: keyword,
      page: 1
    },
    success: (res) => {
      if (res.data && res.data.data) {
        console.log(res.data);
        this.setData({ photoList: res.data.data.data,kvimg: res.data.data.kv_img });
      } else {
        wx.showToast({ title: '数据格式异常', icon: 'none' });
      }
    },
    fail: () => {
      wx.showToast({ title: '加载失败', icon: 'none' });
    },
    complete: () => {
      wx.hideLoading();
    }
  });
},

  // 投票
  vote(e) {
    const user_id = getApp().globalData.userInfo.userID;
    const id = e.currentTarget.dataset.id;
    wx.showLoading({ title: '投票中...' });
    wx.request({
      url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/dovote',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'  
      },
      data: {
        user_id,
        vote_user_id:id
      },
      success: (res) => {
        console.log('--------投票成功0---', res.data.errorcode);
        if (res.data.errorcode.code !== 0) {
          let message = res.data.errorcode.message;
          if (message.indexOf('succ') > -1) {
            wx.showToast({ title: '投票成功', icon: 'none', duration: 1000});
              setTimeout(() => {
              this.getPhotos();
          }, 1000);
          } else {
            wx.showToast({ title: res.data.errorcode.message, icon: 'none',duration: 1000});
          }
        
          return;
        }
        // wx.showToast({ title: '投票成功' ,icon: 'none'});
      },
      complete: () => {
      }
    });
  },
// 昵称输入
onNicknameInput(e) {
  this.setData({ nickname: e.detail.value });
},
  onTurenameInput(e) { 
    this.setData({ trueName: e.detail.value });
  },
  onPhoneeInput(e){
    this.setData({ phoneno: e.detail.value });
  },
  // 打开上传弹窗
  openUpload() {
    const user_id = getApp().globalData.userInfo.userID;

  if (!user_id) {
    wx.showToast({ title: '用户未登录', icon: 'none' });
    return;
  }

  wx.showLoading({ title: '加载中...' });
  wx.request({
    url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/is_can_upload', 
    method: 'GET',
    data: { user_id },
    success: (res) => {
      console.log('--------是否可以上传---', res.data);
      if (res.data && res.data.data.upload_info) {
        const info = res.data.data.upload_info;
        if (info.image) {
          // 用户已上传过照片
          this.setData({
            historyImage: info.image,
            nickname: info.username,
            historyVotes: info.vote_num,
            vote_status:info.status,
            disableNickname: info.vote_num > 0,
            showSubmit: info.vote_num == 0,
            uploadImage: '', // 防止重复
            showUpload: true
          });
        } else {
          // 没有上传过
          this.setData({
            historyImage: '',
            nickname: '',
            historyVotes: 0,
            disableNickname: false,
            showSubmit: true,
            uploadImage: '',
            showUpload: true
          });
        }
      } else {
        wx.showToast({ title: '数据异常', icon: 'none' });
      }
    },
    fail: () => {
      wx.showToast({ title: '加载失败', icon: 'none' });
    },
    complete: () => {
      wx.hideLoading();
    }
  });
},

  // 关闭上传弹窗
  closeUpload() {
    this.setData({ showUpload: false, uploadImage: '' });
  },

  // 选择图片
  chooseImage() {
    if (! this.data.showSubmit) { return; }
      wx.chooseImage({
        count: 1,
        success: (res) => {
          const filePath = res.tempFilePaths[0];
          const fileSize = res.tempFiles[0].size; // 文件大小（字节）
    
          // 校验大小
          if (fileSize > 3 * 1024 * 1024) {
            wx.showToast({ title: '图片不能超过3M', icon: 'none' });
            return;
          }
          // 校验通过
          this.setData({ uploadImage: filePath, historyImage:''});
                
        }
      });
    
  },

// 提交上传
submitUpload() {
  const { nickname, uploadImage, historyImage,phoneno,trueName } = this.data;
  const user_id = getApp().globalData.userInfo.userID;

  if (!uploadImage && !historyImage) {
    wx.showToast({ title: '请先选择图片', icon: 'none' });
    return;
  }
   if (!trueName) {
    wx.showToast({ title: '请输入姓名', icon: 'none' });
    return;
   }
   if (!phoneno) {
    wx.showToast({ title: '请输入手机号', icon: 'none' });
    return;
  }

  if (!nickname) {
    wx.showToast({ title: '请输入昵称', icon: 'none' });
    return;
  }

  // 如果没有上传图片且票数为0，仅更新昵称
  if (!uploadImage && historyImage ) {
    wx.showLoading({ title: '修改中...' });
    wx.request({
      url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/submitinfo',
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      data: {
        truename:trueName,
        phoneno:phoneno,
        username: nickname,
        user_id: user_id
      },
      success: (res) => {
        console.log('上传成功0-------1-2------', res);
        if (res.data.errorcode.message == 'succ') {
          wx.showToast({ title: '编辑成功' , icon: 'none',duration: 2000 });
        }
        this.closeUpload();
        setTimeout(() => {
          this.getPhotos();
        }, 2000);
      },
      fail: () => {
        wx.showToast({ title: '更新失败', icon: 'none' ,duration: 2000});
      },
      complete: () => {
      }
    });
    return;
  }
 // 如果选择了新图片，使用上传图片的接口
 if (uploadImage) {
  wx.showLoading({ title: '上传中...' });
  wx.uploadFile({
    url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/submitinfo',
    filePath: uploadImage, // 使用选中的新图片
    name: 'image',  // 表单字段名
    formData: {
      truename:trueName,
      phoneno:phoneno,
      username: nickname,
      user_id: user_id
    },
    success: (res) => {
      wx.showToast({ title: '上传成功' , icon: 'none' ,duration: 2000});
      this.closeUpload();
       setTimeout(() => {
          this.getPhotos();
        }, 2000);
    },
    fail: () => {
      wx.showToast({ title: '上传失败', icon: 'none',duration: 2000 });
    },
    complete: () => {
    }
  });
} else {
  // 没有修改图片，使用历史图片（如果有），仅更新昵称
  wx.showLoading({ title: '更新昵称中...' });
  wx.request({
    url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/submitinfo',
    method: 'POST',
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    data: {
      username: nickname,
      user_id: user_id
    },
    success: () => {
      wx.showToast({ title: '昵称更新成功' });
      this.closeUpload();
      this.getPhotos();
    },
    fail: () => {
      wx.showToast({ title: '更新失败', icon: 'none' });
    },
    complete: () => {
      wx.hideLoading();
    }
  });
}
},

  // 跳转详情
  goDetail(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `./detail?info=${encodeURIComponent(JSON.stringify(item))}`
    });
  },
    onShareAppMessage() {
    return {
      title: "投票活动",
      path: "/pages/vote/index",
    };
  },

  onShareTimeline() {
    return {
      title: "投票活动",
      path: "/pages/vote/index",
    };
  }
});
